//
//  LXTabBarController.m
//  bgms_p
//
//  Created by xiao.zhao@lachesis-mh.com on 16/2/23.
//  Copyright © 2016年 xiao.zhao@lachesis-mh.com. All rights reserved.
//

#import "LXTabBarController.h"
#import "LXLoginVC.h"
#import "LXMineViewController.h"
#import "GLMusicListViewController.h"
#import "LXMessageViewController.h"
#import "LXContactsViewController.h"
#import "LXMaikeViewController.h"
#import "AppDelegate.h"
#import "BLETransDeviceSingleton.h"
#import "LXTabBar.h"


@interface LXTabBarController () <UITabBarControllerDelegate, BLETransDeviceSingletonDelegate>
{
    BLETransDeviceSingleton *bleCtl;
}

@property (nonatomic, strong) LXTabBar *lx_tabbar;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger connectIndex;

@end

@implementation LXTabBarController

+ (instancetype)instance {
    AppDelegate *delegete = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIViewController *vc = delegete.window.rootViewController;
    if ([vc isKindOfClass:[LXTabBarController class]]) {
        return (LXTabBarController *)vc;
    } else {
        return nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    bleCtl = [BLETransDeviceSingleton sharedInstance];
    bleCtl.delegate = self;
    [self addViewControllers];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.view.frame = [UIScreen mainScreen].bounds;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)addViewControllers
{
    NSArray *titleNames = @[@"MUSIC", @"LIGHT MODE", @"MIC VOLUME", @"LINK", @"BATTERY"];
    
    GLMusicListViewController *homeVC = [[GLMusicListViewController alloc] initWithNibName:NSStringFromClass([GLMusicListViewController class]) bundle:nil];
    homeVC.title = titleNames[0];
    LXWhiteColorNavigationController *homeNav = [[LXWhiteColorNavigationController alloc] initWithRootViewController:homeVC];
    
    LXMessageViewController *messageVC = [[LXMessageViewController alloc] initWithNibName:NSStringFromClass([LXMessageViewController class]) bundle:nil];
    messageVC.title = titleNames[1];
    LXWhiteColorNavigationController *messageNav = [[LXWhiteColorNavigationController alloc] initWithRootViewController:messageVC];
    
    LXMaikeViewController *maikeVC = [[LXMaikeViewController alloc] initWithNibName:NSStringFromClass([LXMaikeViewController class]) bundle:nil];
    maikeVC.title = titleNames[2];
    LXWhiteColorNavigationController *maikeNav = [[LXWhiteColorNavigationController alloc] initWithRootViewController:maikeVC];
    
    LXContactsViewController *patientsVC = [[LXContactsViewController alloc] initWithNibName:NSStringFromClass([LXContactsViewController class]) bundle:nil];
    patientsVC.title = titleNames[3];
    LXWhiteColorNavigationController *patientsNav = [[LXWhiteColorNavigationController alloc] initWithRootViewController:patientsVC];
    
    LXMineViewController *mineVC = [[LXMineViewController alloc] initWithNibName:NSStringFromClass([LXMineViewController class]) bundle:nil];
    mineVC.title = titleNames[4];
    LXWhiteColorNavigationController *mineNav = [[LXWhiteColorNavigationController alloc] initWithRootViewController:mineVC];
    
    self.viewControllers = @[homeNav, messageNav, maikeNav, patientsNav, mineNav];
    
    NSInteger offsetHeight = kScreenHeight > 800 ? 39 : 0;
    CGRect frame = CGRectMake(0, kScreenHeight - 54 - offsetHeight, kScreenWidth, 54 + offsetHeight);
    _lx_tabbar = [[LXTabBar alloc] initWithFrame:frame];
    _lx_tabbar.translucent = NO;
    
    [_lx_tabbar drawAroundViewWithLocation:DrawTop color:kAppLinesColor insets:UIEdgeInsetsMake(0, 0, -0.5, 0)];
    [self setValue:_lx_tabbar forKeyPath:@"tabBar"];
    
    [self.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull vc, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *selectImageName = [NSString stringWithFormat:@"iconTabbar_%u_pre", idx+1];
        NSString *normalImageName = [NSString stringWithFormat:@"iconTabbar_%u_nor", idx+1];

        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"" image:[[UIImage imageNamed:normalImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:selectImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        NSDictionary *AttributeNormalDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                            kAppGrayTextColor, NSForegroundColorAttributeName,
                                            [UIFont lx_systemFontOfSize:11], NSFontAttributeName, nil];
        NSDictionary *AttributeSelectDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                            kAppThemeColor, NSForegroundColorAttributeName,
                                            [UIFont lx_systemFontOfSize:11], NSFontAttributeName, nil];
        [item setTitleTextAttributes:AttributeNormalDic forState:UIControlStateNormal];
        [item setTitleTextAttributes:AttributeSelectDic forState:UIControlStateSelected];
        vc.tabBarItem = item;
    }];
    
    self.tabBar.shadowImage = [UIImage imageWithColor:[UIColor clearColor]];
    self.tabBar.backgroundImage = [UIImage imageWithColor:[UIColor clearColor]];
    self.tabBar.barTintColor = [UIColor whiteColor];//背景颜色为红色
    self.delegate = self;
}

- (UIViewController *)appRootViewController
{
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

#pragma mark -
#pragma mark -UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    NSInteger index = [self.viewControllers indexOfObject:viewController];
    if(index == 2)
    {

    }
    
    return YES;
}

- (void)BLETransDeviceSingletonConnected:(BOOL)connected
{
    if (connected) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)BLETransDeviceSingletonDisConnected:(BOOL)connected
{
    if (self.tabBarController.selectedIndex != 2) {
        self.timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(connectRun) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
        [bleCtl reConnectPeriheral];
    }
}

- (void)connectRun
{
    self.connectIndex += 1;
    if (self.connectIndex == 3) {
        [self.timer invalidate];
        self.timer = nil;
        LXLoginVC *loginVC = [[LXLoginVC alloc] init];
        LXThemeColorNavigationController *themeNav = [[LXThemeColorNavigationController alloc] initWithRootViewController:loginVC];
        self.view.window.rootViewController = themeNav;
    } else {
        [bleCtl reConnectPeriheral];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
